//
//  ZQRefieshControl.swift
//  ZQWeibo
//
//  Created by summer的Dad on 16/11/19.
//  Copyright © 2016年 summer的Dad. All rights reserved.
//

import UIKit

enum refieshe : Int {
    case Nomal = 0
    case Already
    case Refreshing
}



private let refieshHeight : CGFloat = 60



class ZQRefieshControl: UIControl {
 
    //枚举处理Kvo执行逻辑
    
    var enumtype :refieshe = .Nomal{
        didSet{
            
            switch enumtype {
            case .Nomal:
                //leble显示
                tipLable.text = "下拉刷新"
                //小菊花转动
                activiti.stopAnimating()
                arrayIcon.isHidden = false
                //修改小箭头的方向
                UIView.animate(withDuration: 0.25, animations: {
                    //恢复
                    self.arrayIcon.transform = CGAffineTransform.identity
                })
                
                if oldValue == .Refreshing{
                    
                    UIView.animate(withDuration: 0.5, animations: {
                        self.scrollView?.contentInset.top = self.scrollView!.contentInset.top - refieshHeight
                    })
                    
                    
                    
                }
            case .Already:
                print("准备刷新状态")
                tipLable.text = "松手刷新"
                
                //修改小箭头的方向
                UIView.animate(withDuration: 0.25, animations: {
                    //形变
                    self.arrayIcon.transform = CGAffineTransform.init(rotationAngle:CGFloat(Double(M_PI)))
                })
                
                
                
                
            case .Refreshing:
                print("刷新中...")
                //停止刷新
                activiti.startAnimating()
                arrayIcon.isHidden = true
                
                //发出
                    sendActions(for: .valueChanged)
                
                //让lable刷新回去停留
                UIView.animate(withDuration: 0.2, animations: {
                    
                    self.scrollView?.contentInset.top = self.scrollView!.contentInset.top + refieshHeight
                    
                })
                
      
            
                
            }
          
        }
    }
    
    func endReshing() {
        
        //异步...目的是让lable延迟
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5 ) {
            
            self.enumtype = .Nomal
            
            
            
        }
        
    }
    //设置固定大小
    override init(frame: CGRect) {
       
        
        let rect = CGRect(x: 0, y: -refieshHeight, width: ScreenWidth, height: refieshHeight)
        
         super.init(frame: rect)
        
        //self.backgroundColor = UIColor.gray
        
        setupUI()
    }
    
    
    func setupUI(){
        
        addSubview(backImage)
        addSubview(tipLable)
        addSubview(arrayIcon)
        addSubview(activiti)
        
        //约束
        tipLable.snp.makeConstraints { (make) in
            
            make.centerX.equalTo(self.snp.centerX).offset(20)
            make.centerY.equalTo(self.snp.centerY)
            
        }
        arrayIcon.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.snp.centerX).offset(-20)
            make.centerY.equalTo(self.snp.centerY)
        }
        activiti.snp.makeConstraints { (make) in
            make.center.equalTo(arrayIcon)
        }
        backImage.snp.makeConstraints { (make) in
            make.leading.bottom.trailing.equalTo(self)
            
        }
        
        
 
    }
    
    //添加监听方法
    override func willMove(toSuperview newSuperview: UIView?) {
        
        super.willMove(toSuperview: newSuperview)
        if let fatherView = newSuperview as? UIScrollView{
        
            //设置观察者
            self.scrollView = fatherView
            self.scrollView?.addObserver(self, forKeyPath: "contentOffset", options: [.new], context: nil)
        }
    }
  
    
    
    //监听方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
          let offset =  self.scrollView?.contentOffset.y ?? 0
        
          let tageteoffsetY = -((self.scrollView!.contentInset.top) + refieshHeight)
  
        //判断是否拖拽
        if (scrollView?.isDragging)!{
            //判断是否刷新
            if enumtype == .Nomal && offset < tageteoffsetY {
                
                
                enumtype = .Already
                
             
              }else if enumtype == .Already && offset > tageteoffsetY{
                
              
                
                enumtype = .Nomal
                
            }
            
            
        }else{
        
            if enumtype == .Already{
                
                enumtype = .Refreshing
            }
   
        }
        
        
        
    }

    
    
    
    
    
    
    
    
    //懒加载控件
    var scrollView : UIScrollView?
    private lazy var tipLable : UILabel = UILabel(title: "下来起飞", fontSize: 14, textColor: UIColor.orange)
    //箭头
    private lazy var arrayIcon : UIImageView = UIImageView(image: #imageLiteral(resourceName: "tableview_pull_refresh"))
    //小菊花
    private lazy var activiti : UIActivityIndicatorView = UIActivityIndicatorView()
    
    private lazy var  backImage : UIImageView = UIImageView(image: UIImage(named:"refreshbg"))
    
    
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

}
